package de.hs_fulda.SoftComputing.Gogol.Wasserkraft;

import java.awt.Font;
import java.awt.image.BufferedImage;
import java.io.InputStream;

import net.sourceforge.jFuzzyLogic.FIS;
import net.sourceforge.jFuzzyLogic.rule.Variable;

import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.XYPlot;

public class WasserkraftFuzzyController {
  private FIS controller;
  private boolean changed;
  public WasserkraftFuzzyController (InputStream fclFile) {
    controller = FIS.load(fclFile, true);    
    // Error while loading?
    if( controller == null ) { 
        System.err.println("Can't load file: '" + fclFile+ "'");
        return;
    }
    
    changed = false;
  }
  public void setInputVariable (INPUT var, double value) {
    controller.setVariable(var.toString(), value);
    changed = true;
  }
  public double getOutputVariable (OUTPUT var) {
    Variable variable;
    if (changed) {
      controller.evaluate();     
      changed = false;
    }
    variable = controller.getVariable(var.toString());
    variable.defuzzify();	
    return controller.getVariable(var.toString()).getValue();
  }
  public BufferedImage getInputChart(INPUT var) {
    int lower, upper;
    Variable fuzzyVar; 

    fuzzyVar = controller.getVariable(var.toString());
    JFreeChart chart = fuzzyVar.chart(false);
    chart.removeLegend();
    chart.getTitle().setFont(new Font(null, Font.BOLD, 10));
    lower = 0;
    upper = 0;
    switch (var) {
      case PegelZufluss:
      case PegelAblass:
	upper = 15;
	break;
      case PegelStausee:
	upper = 100;
	break;
      case Strombedarf:
	upper = 100;
	break;
    }
    chart.getXYPlot().getDomainAxis().setRange(lower, upper);
    chart.getXYPlot().getRangeAxis().setLabel("");
    chart.getXYPlot().getRangeAxis().setTickLabelsVisible(false);
    chart.getXYPlot().getDomainAxis().setLabel("");
    return chart.createBufferedImage(190, 120);
  }
  public BufferedImage getOutputChart(OUTPUT var) {
    Variable fuzzyVar = controller.getVariable(var.toString());
    JFreeChart chart = fuzzyVar.chart(false);
    XYPlot xyPlot = chart.getXYPlot();
    
    chart.removeLegend();
    chart.getTitle().setFont(new Font(null, Font.BOLD, 10));    
    xyPlot.getDomainAxis().setRange(0, 100);
    xyPlot.getRangeAxis().setLabel("");
    xyPlot.getDomainAxis().setLabel("");
    xyPlot.getRangeAxis().setTickLabelsVisible(false);
    
    return chart.createBufferedImage(190, 150);
  }
}
